﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory;

namespace BookTheBook.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class BookTheBookApplication : HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Book", action = "Index", Id = 1 });  // Parameter defaults, can pass additional. Book as default - to ease up development
        }

        protected void Application_Start()
        {
            IApplicationContext ctx = ContextRegistry.GetContext();
            SpringControllerFactory.Init(ctx);
            ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure(); 
        }
    }

    public class SpringControllerFactory : DefaultControllerFactory
    {
        private static IObjectFactory _factory;
        //not to flood with Exceptions where using Spring .NET (which behavior is ridiciolus)
        private static readonly IList<string> _listOfSpringDefinedControllers = new List<string>
                                        {
                                          "Book", //for db-fetched
                                          "Search"  //for amazon-fetched                          
                                        };

        public static void Init(IApplicationContext applicationContext)
        {
            _factory = applicationContext;
        }

        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            if (_listOfSpringDefinedControllers.Contains(controllerName))
            return (IController)_factory.GetObject(controllerName + "Controller");
        
            return base.CreateController(requestContext, controllerName);
        }

        public override void ReleaseController(IController controller)
        {
            if (controller is IDisposable)
            {
                (controller as IDisposable).Dispose();
            }
        }
    }
 
}